//
//  KAAddBillViewController.m
//  KeepAccounts
//
//  Created by honeyrr on 2017/10/5.
//  Copyright © 2017年 honeyrr. All rights reserved.
//

#import "KAAddBillViewController.h"
#import "KABillItem.h"
#import "KABillCollectionViewCell.h"
#import "KADataBaseModel.h"
#import "KAEditItemViewController.h"
#import "CalculatorView.h"

@interface KAAddBillViewController ()<UICollectionViewDelegate, UICollectionViewDataSource, CalculatorViewDelegate>

@property(nonatomic, strong) UISegmentedControl *segmentControl;
@property(nonatomic, strong) NSMutableArray *billItems;
@property(nonatomic, strong) NSArray *displayItems;
@property(nonatomic, strong) UICollectionView *collectionView;
@property (nonatomic,strong)CalculatorView *calview;
@property(nonatomic, strong) KABillItem *billItem;

@property(nonatomic ,copy) NSString *remark;

@end

static NSString *const addBillCollectionViewCell = @"addBillCollectionViewCell";

@implementation KAAddBillViewController

-(void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    NSMutableArray *incomeMarr = [[KAReadFile sharedInstance] readPlistFile:KAIncomePlistPath];
    NSMutableArray *outlayMarr = [[KAReadFile sharedInstance] readPlistFile:KAOutlayPlistPath];
    
    KABillItem *billItem = [[KABillItem alloc]init];
    billItem.imageName = @"addItem";
    billItem.titleName = @"添加";
    [incomeMarr addObject:billItem];
    [outlayMarr addObject:billItem];
    [self.billItems addObjectsFromArray:@[incomeMarr,outlayMarr]];
    [self segmentedControlClicked:self.segmentControl];
    [self.collectionView reloadData];
}

-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:YES];
    
    if (self.dbModel != nil) {
        self.calview.image = [UIImage imageNamed:self.dbModel.imageName];
        self.calview.typeName = self.dbModel.name;
        if ([self.dbModel.billtype isEqualToString:@"支出"]) {
            [self.segmentControl setSelectedSegmentIndex:1];
        } else {
            [self.segmentControl setSelectedSegmentIndex:0];
        }
        [self segmentedControlClicked:self.segmentControl];
    }
    
}

-(void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:YES];
    
}

//计算器界面
- (CalculatorView *)calview {
    if (!_calview) {
        _calview = [[CalculatorView alloc] initWithFrame:CGRectMake(0, self.view.frame.size.height * 0.6, self.view.frame.size.width, self.view.frame.size.height * 0.4)];
        _calview.delegate = self;
        _calview.imageViewSize = CGSizeMake(50, 50);
    }
    return _calview;
}

-(KABillItem *)billItem
{
    if (!_billItem) {
        _billItem = [[KABillItem alloc]init];
    }
    return _billItem;
}

- (void)viewDidLoad {
    [super viewDidLoad];
   
    [self setUpUI];
    [self.view addSubview:self.calview];
}

//-(void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
//{
//    [self listScrollToBottom];
//}

-(void) setUpUI
{
    self.view.backgroundColor = [UIColor whiteColor];
    self.navigationItem.titleView = self.segmentControl;
    
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithTitle:@"备注" style:UIBarButtonItemStylePlain target:self action:@selector(remarkContent)];
    [self setContentViewUI];
}

-(void)remarkContent
{
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"备注信息" message:@"" preferredStyle:UIAlertControllerStyleAlert];
    [alert addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil]];
    //添加文本框
    [alert addTextFieldWithConfigurationHandler:^(UITextField * _Nonnull textField) {
        textField.textColor = [UIColor blackColor];
        textField.placeholder = @"填写此账单的详细信息";
    }];
    //确认按钮
    [alert addAction:[UIAlertAction actionWithTitle:@"确认" style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) {
        self.calview.dbModel.remark = alert.textFields[0].text;
    }]];
    [self presentViewController:alert animated:YES completion:nil];
}

//计算界面下降
- (void)listScrollToBottom {
    [UIView animateWithDuration:0.5 delay:0 options:UIViewAnimationOptionCurveLinear animations:^{
        self.calview.frame = CGRectMake(0, CGRectGetHeight(self.view.frame)-CGRectGetHeight(self.calview.frame)/5, self.calview.frame.size.width, self.calview.frame.size.height);
    } completion:nil];
}
#pragma mark - CalculatorViewDelegate
//保存成功
- (void)tallySaveCompleted {
    //随机转场动画
    NSArray *tanArray = @[@"pageCurl",@"pageUnCurl",@"rippleEffect",@"suckEffect",@"cube",@"oglFlip"];
    NSString *anStr = tanArray[arc4random()%tanArray.count];
    self.navigationController.modalTransitionStyle = UIModalTransitionStyleCrossDissolve;
    CATransition *tran = [CATransition animation];
    tran.duration = 0.5;
    tran.type = anStr;
    tran.subtype = kCATransitionFromLeft;
    [self.navigationController.view.layer addAnimation:tran forKey:nil];
    [self.navigationController popViewControllerAnimated:NO];
    
}
//保存失败
- (void)tallySaveFailed {
    UIAlertController *alertVC =[UIAlertController alertControllerWithTitle:@"提示" message:@"请选择类别并输入金额" preferredStyle:UIAlertControllerStyleAlert];
    [alertVC addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:nil]];
    [self presentViewController:alertVC animated:YES completion:nil];
}

//返回位置
- (void)backPositionWithAnimation {
    [UIView animateWithDuration:0.5 delay:0 options:UIViewAnimationOptionCurveLinear animations:^{
        self.calview.frame = CGRectMake(0, self.view.frame.size.height * 0.6, self.view.frame.size.width, self.view.frame.size.height * 0.4);
    } completion:nil];
}

-(NSMutableArray *)billItems
{
    if (!_billItems) {
        _billItems = [NSMutableArray array];
        
    }
    return _billItems;
}

-(NSArray *)displayItems
{
    if (!_displayItems) {
        _displayItems = [NSArray array];
    }
    return _displayItems;
}

-(UISegmentedControl *)segmentControl
{
    if (!_segmentControl) {
        UISegmentedControl *sc = [[UISegmentedControl alloc]initWithItems:@[@"收入", @"支出"]];
        sc.bounds = CGRectMake(0, 70, 135, 30);
        sc.center = CGPointMake(KAScreenW / 2, 90);
        //默认no 瞬间弹起来，不维持选中状态
        //sc.momentary=YES;
        //默认选中第几个
        sc.selectedSegmentIndex = 0;
        //ios 5.0 以后才有的，根据内容的多少 去改变 宽度,no 不改变
        sc.apportionsSegmentWidthsByContent = YES;
        [sc addTarget:self action:@selector(segmentedControlClicked:) forControlEvents:UIControlEventValueChanged];
        _segmentControl = sc;
    }
    return _segmentControl;
}

-(void) segmentedControlClicked:(UISegmentedControl *)sender
{
    NSInteger index = sender.selectedSegmentIndex;
    self.displayItems = self.billItems[index];
    [self.collectionView reloadData];
}

-(void) setContentViewUI
{
    [self.collectionView registerNib:[UINib nibWithNibName:NSStringFromClass([KABillCollectionViewCell class]) bundle:nil] forCellWithReuseIdentifier:addBillCollectionViewCell];
    [self.view addSubview:self.collectionView];
}

-(UICollectionView *)collectionView
{
    if (!_collectionView) {
        UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc]init];
        layout.itemSize = CGSizeMake(50, 82);
        layout.sectionInset = UIEdgeInsetsMake(2, 3, 1, 3);
        UICollectionView *cv = [[UICollectionView alloc]initWithFrame:CGRectMake(0, 0, KAScreenW, KAScreenH - self.calview.bounds.size.height -10) collectionViewLayout:layout];
        cv.backgroundColor = [UIColor whiteColor];
        cv.delegate = self;
        cv.dataSource = self;
        _collectionView = cv;
    }
    return _collectionView;
}

-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return self.displayItems.count;
}

-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    KABillCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:addBillCollectionViewCell forIndexPath:indexPath];
    cell.billItem = self.displayItems[indexPath.row];
    return cell;
}

-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row == self.displayItems.count - 1) {
        KAEditItemViewController *editItem = [KAEditItemViewController new];
        NSString *billType = [self.segmentControl titleForSegmentAtIndex:self.segmentControl.selectedSegmentIndex];
        editItem.billType = billType;
        [self.navigationController pushViewController:editItem animated:YES];
    } else {
        NSDateFormatter *date = [[NSDateFormatter alloc] init];
        date.dateFormat = @"yyyy-MM-dd";
        NSString *today = [date stringFromDate:[NSDate date]];
        
        NSDateFormatter *time = [[NSDateFormatter alloc] init];
        time.dateFormat = @"HH:mm";
        NSString *nowTime = [time stringFromDate:[NSDate date]];
        if ([self.currentDate isEqualToString:today]) {
            self.currentDate = today;
        }
        NSString *type = [self.segmentControl titleForSegmentAtIndex:self.segmentControl.selectedSegmentIndex];
        
        _billItem = self.displayItems[indexPath.row];
        UIImage *image = [UIImage imageNamed:_billItem.imageName];
        NSString *text = _billItem.titleName;
        
        KADataBaseModel *model = [[KADataBaseModel alloc]init];
        model.imageName = _billItem.imageName;
        model.name = _billItem.titleName;
        model.date = self.currentDate;
        model.time = nowTime;
        model.billtype = type;
        
        UIImageView *animateImage = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 40, 40)];
        animateImage.image = image;
        [self.view addSubview:animateImage];
        
        __block CGPoint imgPoint;
        self.calview.positionInViewBlock = ^(CGPoint point){
            imgPoint = point;
        };
        
        //给计算器界面传值
        self.calview.imageViewSize = CGSizeMake(40, 40);
        self.calview.image = image;
        self.calview.typeName = text;
        self.calview.dbModel = model;
        if (self.dbModel == nil) {
            self.calview.isBillExist = false;
        } else {
            self.calview.isBillExist = true;
        }
        
        //设置贝塞尔曲线路径动画
        UIBezierPath *path = [UIBezierPath bezierPath];
        [path moveToPoint:animateImage.center];
        [path addCurveToPoint:imgPoint controlPoint1:CGPointMake(animateImage.frame.origin.x + 200, animateImage.frame.origin.y + 100 ) controlPoint2:CGPointMake(animateImage.frame.origin.x + 200, animateImage.frame.origin.y + 100 )];
        CAKeyframeAnimation *anmiation0 = [CAKeyframeAnimation animationWithKeyPath:@"position"];
        anmiation0.path = path.CGPath;
        anmiation0.duration = 1;
        anmiation0.removedOnCompletion = NO;
        anmiation0.fillMode = kCAFillModeForwards;
        [animateImage.layer addAnimation:anmiation0 forKey:nil];
        [NSTimer scheduledTimerWithTimeInterval:1 repeats:NO block:^(NSTimer * _Nonnull timer) {
            [animateImage removeFromSuperview];
        }];
    }
}

@end
